package com.rose.doorto.footbathpay.controller;


import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.alipay.easysdk.factory.Factory;
import com.alipay.api.AlipayApiException;
import com.rose.doorto.common.exception.BizCodeEnum;
import com.rose.doorto.common.exception.BizException;
import com.rose.doorto.footbathdoor.enums.OrderStatusEnum;
import com.rose.doorto.footbathdoor.enums.PayType;
import com.rose.doorto.footbathdoor.pojo.Order;
import com.rose.doorto.footbathpay.config.AlipayTemplateold;
import com.rose.doorto.footbathpay.fegin.OrderFeginRemoteService;
import com.rose.doorto.footbathpay.vo.AlipayVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author 李庆超
 * @email 1481791489@qq.com
 * @Package：com.rose.doorto.footbathdoor.controler
 * @Project：door-to-door
 * @name：AliPayController
 * @date 2024/08/09 2024/8/9:14:19:
 */
//@RestController
@Slf4j
@Controller
@RequestMapping("/hhhhhhhhhhhhhhhhhhhalipay")
public class AliPayController {


    @Resource
    AlipayTemplateold alipayTemplate;

    @Autowired
    private OrderFeginRemoteService feginRemoteService;

    /**
     * 订单支付接口， 核心是调用支付宝的 Factory.Payment.Page().pay() 方法
     *
     * @param subject     支付对象信息
     * @param outTradeNo  订单号
     * @param totalAmount 订单金额
     * @return
     */
    @RequestMapping("/pay")
    public String pay(String subject, String outTradeNo, String totalAmount) {
        AlipayTradePagePayResponse response;
        try {
            response = Factory.Payment.Page().pay(subject, outTradeNo, totalAmount, "");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return response.getBody();
    }

    /**
     * 支付回调接口，如果支付成功，支付宝将会请求此接口，将成功信息返回
     *
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/notify")
    public String notify(HttpServletRequest request) throws Exception {
        String tradeStatus = request.getParameter("trade_status");

        if (tradeStatus.trim().equals("TRADE_SUCCESS")) {
            Map<String, String> param = new HashMap<>();
            Map<String, String[]> parameterMap = request.getParameterMap();
            for (String name : parameterMap.keySet()) {
                param.put(name, request.getParameter(name));
            }

            // 验证请求的有效性
            if (Factory.Payment.Common().verifyNotify(param)) {
                System.out.println("通过支付宝的验证");
                String orderIdStr = param.get("out_trade_no");
                System.out.println("orderIdStr = " + orderIdStr);
            } else {
                System.out.println("支付验证不通过");
            }
        }
        return "success";
    }




//    @GetMapping(value = "/pay", produces = "text/html")
    @GetMapping(value = "/payOrder/{orderSn}", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String pay(@PathVariable("orderSn") String orderSn) throws AlipayApiException {
        Order order = feginRemoteService.getOrderByOrderSn(orderSn);
        if (order == null){
            return "该订单不存在";
        }else if (order.getStatus()!= OrderStatusEnum.CREATE_NEW.getCode()){
            return "该订单不是待付款状态";
        }
        AlipayVO alipayVO = new AlipayVO();
        //订单号
        alipayVO.setOutTradeNo(orderSn);
        //支付宝支付要求金额必须为小数点后两位
        alipayVO.setTotalAmount(order.getRewardPrice().setScale(2, BigDecimal.ROUND_UP).toString());
        alipayVO.setSubject("广庆到家订单");
        alipayVO.setBody("广庆到家订单");
        order.setPayType(PayType.ALIPAY.getCode());
        try {
            String response = alipayTemplate.pay(alipayVO);
            log.info("支付宝支付响应: {}",response);
            return response;
        }catch (AlipayApiException e){
            log.error("阿里支付失败：{}", e.getMessage());
            throw new BizException(BizCodeEnum.ORDER_PAY_FEILED);
        }
    }

    @PostMapping("/notifys")  // 注意这里必须是POST接口
    public String payNotify(HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
                // System.out.println(name + " = " + request.getParameter(name));
            }

            String tradeNo = params.get("out_trade_no");
            String gmtPayment = params.get("gmt_payment");
            String alipayTradeNo = params.get("trade_no");
            // 支付宝验签
            if (Factory.Payment.Common().verifyNotify(params)) {
                // 验签通过
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));
                // 更新订单状态
            }
        }
        return "success";
    }

}
